package com.zdy.syn;

/**
 * Created by 逸足天涯
 * on 3/9/2020.
 */
//不安全的买票，线程不安全有负数
public class BuyTicket implements Runnable {


    private int ticketNums = 10;
    Boolean flag = true;
    @Override
    public void run() {
        while(flag){
            buy();
        }

    }
    //synchronized, 锁的是this
    public synchronized void buy(){
        //判断是否有票
        if(ticketNums <=0 ){
            flag = false;
            return ;
        }
        //模拟延迟
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"拿到-->"+ticketNums--);
    }

    //主方法
    public static void main(String[] args) {
        BuyTicket Tickets = new BuyTicket();
        new Thread(Tickets,"苦逼的我").start();
        new Thread(Tickets,"牛逼的你").start();
        new Thread(Tickets,"可恶的他").start();
    }
}
